//
//  BCManagerInfoViewController.m
//  BCVersion
//
//  Created by 吴 崧 on 14-2-24.
//  Copyright (c) 2014年 Jungle. All rights reserved.
//

#import "BCManagerInfoViewController.h"
#import "ClientManagerModel.h"



#import "ClientProdutModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "BCCommentViewController.h"
#import "ScoreShowImage.h"
#import "ClientCommentModel.h"
#import "BCMEditProductViewController.h"
#import "MJRefreshFooterView.h"
#import "ManagerDetailCell.h"
#import "CommentInfoCell.h"
#import "ManagerProductCell.h"
static NSString *managerInfIdentifier = @"ManagerDetailCell";
static NSString *ptInfoIdentifier = @"ManagerProductCell";
static NSString *commentIdentifier = @"CommentInfoCell";

@interface BCManagerInfoViewController ()
@property(nonatomic,strong)NSArray *commentDetail;
@property(nonatomic,strong)NSArray *managerInfo;
@property(nonatomic,strong)NSArray *ptDataSource;
@property(nonatomic,strong)MJRefreshFooterView *footer;
@property(assign,nonatomic)int startIndex;
@end

@implementation BCManagerInfoViewController


- (instancetype)initWithUid:(NSNumber *)uid
{
    self = [super init];
    if (self) {
        _startIndex = 0;
        _uid = uid;
        _ptDataSource = [NSArray array];
        _managerInfo = [NSArray array];
        _commentDetail = [NSArray array];
        _footer = nil;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // Do any additional setup after loading the view from its nib.
}
- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)downLoadDetailInfo
{
    __weak typeof(self)weakSelf = self;
    [BCProgressHUD showWithTile:@"下载中" animated:YES];
    
    [BCNetworkClient adsInfo:self.uid
                        type:TYPE_DETAIL
                reqFriendUid:USER_MANAGER.uid
                     success:^(NSDictionary *info) {
                         ClientManagerModel *model = [[ClientManagerModel alloc]initWithDataSource:info];
                         weakSelf.isFriendBinded = model.isFriendBinded;
                         weakSelf.managerInfo = @[[[ClientManagerModel alloc]initWithDataSource:info]];
                         [weakSelf.tableView reloadSections:[[NSIndexSet alloc]initWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
                         [weakSelf downLoadPt];
                     } failure:^(NSError *error) {
                         [UIAlertView showWithTitle:@"失败"
                                            message:[NSString  stringWithFormat:@"%@",error.userInfo]
                                  cancelButtonTitle:@"确定" otherButtonTitles:@[@"继续下载"]
                                           tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                                               if (buttonIndex == 1) {
                                                   [weakSelf downLoadDetailInfo];
                                               }
                                  }];
                         [BCProgressHUD hideWithError:error animated:NO];
                     }];
}


- (void)downLoadPt
{
    __weak typeof(self)weakSelf = self;
    [BCNetworkClient product:self.uid
                        type:TYPE_LIST
                       start:0
                       limit:10 success:^(NSNumber *total, NSArray *products) {
                        weakSelf.ptDataSource = [ClientProdutModel modelsWithDataSource:products];;
                           [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
                           [weakSelf donwLoadComment];
                       } failure:^(NSError *error) {
                           [UIAlertView showWithTitle:@"失败"
                                              message:[NSString  stringWithFormat:@"%@",error.userInfo]
                                    cancelButtonTitle:@"确定" otherButtonTitles:@[@"继续下载"]
                                             tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                                                 if (buttonIndex == 1) {
                                                     [weakSelf donwLoadComment];
                                                 }
                                             }];
                            [BCProgressHUD hideWithError:error animated:NO];
                       }];

}


-(void)donwLoadComment
{
    __weak typeof(self)weakSelf = self;
    [BCNetworkClient comment:self.uid
                        type:TYPE_LIST
                       start:self.startIndex
                       limit:SearchLimit
                     success:^(NSNumber *total, NSNumber *score, NSArray *comments) {
                         [BCProgressHUD hideAnimated:YES];
                         weakSelf.commentDetail = [NSArray array];
                         if (comments.count > 0) {
                             weakSelf.commentDetail = [weakSelf.commentDetail arrayByAddingObjectsFromArray:[ClientCommentModel modelsWithDataSource:comments]];
                             weakSelf.startIndex += comments.count;
                              [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
                         }
                         
                     } failure:^(NSError *error) {
                         [UIAlertView showWithTitle:@"失败"
                                            message:[NSString  stringWithFormat:@"%@",error.userInfo]
                                  cancelButtonTitle:@"确定" otherButtonTitles:@[@"继续下载"]
                                           tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                                               if (buttonIndex == 1) {
                                                   [weakSelf donwLoadComment];
                                               }
                                           }];
                          [BCProgressHUD hideWithError:error animated:NO];
                     }];
    if (_footer == nil) {
        _footer = [MJRefreshFooterView footer];
        _footer.scrollView = self.tableView;
        __weak typeof(self) weaSelf = self;
        
        _footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
            [BCNetworkClient comment:weaSelf.uid
                                type:TYPE_LIST
                               start:weaSelf.startIndex
                               limit:SearchLimit
                             success:^(NSNumber *total, NSNumber *score, NSArray *comments) {
                                 [BCProgressHUD hideAnimated:NO];
                                 if (comments.count > 0) {
                                     weakSelf.commentDetail = [weakSelf.commentDetail arrayByAddingObjectsFromArray:[ClientCommentModel modelsWithDataSource:comments]];
                                     weakSelf.startIndex += comments.count;
                                     [weaSelf doneReFreshWithView:refreshView
                                                       WithSucess:YES];
                                     
                                 }else
                                 {
                                    
                                     [BCProgressHUD showWithTile:@"暂无更多评论" animated:NO];
                                     [BCProgressHUD hideAnimated:YES];
                                     [weaSelf doneReFreshWithView:refreshView
                                                       WithSucess:NO];
                                 }
                                 
                             } failure:^(NSError *error) {
                          
                                 [BCProgressHUD hideWithError:error animated:NO];
                             }];
        

        };
        
}
}

- (void)doneReFreshWithView:(MJRefreshBaseView *)refreshView
WithSucess:(BOOL)sucess;
    {
        // 刷新表格
        if (sucess) {
           [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            
        }
        [refreshView endRefreshing];
        [refreshView endRefreshingWithoutIdle];
    }
    
    

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.managerInfo.count ==  0) {
        [self downLoadDetailInfo];
    }else
    {
        [self downLoadPt];
    }
    
}

- (IBAction)comment:(id)sender {
    BCCommentViewController *comment  = [[BCCommentViewController alloc]initWithTaget:self.uid];
    self.startIndex = 0;
    [self.navigationController pushViewController:comment animated:YES];
}


- (IBAction)relationBtnPressed:(UIButton *)sender {
    __weak typeof(self)weakSelf = self;
    NSString *typeString = self.isFriendBinded.boolValue?@"remove":@"add";
    [BCNetworkClient friends:USER_MANAGER.auth
                       touid:self.uid
                        type:typeString
                     success:^{

                         weakSelf.isFriendBinded = @(!weakSelf.isFriendBinded.boolValue);
                         NSString *titileString = weakSelf.isFriendBinded.boolValue?@"已添加好友":@"已解除好友";
                         [BCProgressHUD showWithTile:titileString animated:NO];
                         [BCProgressHUD hideAnimated:YES];
                         
                     } failure:^(NSError *error) {
                         
                     }];
}

-(void)setIsFriendBinded:(NSNumber *)isFriendBinded
{
    _isFriendBinded = isFriendBinded;
    if (isFriendBinded.boolValue) {
        [self.relationBtn setImage:[UIImage imageNamed:@"friendRelationYes"] forState:UIControlStateNormal];
    }else
    {
        [self.relationBtn setImage:[UIImage imageNamed:@"friendRelationNo"] forState:UIControlStateNormal];
    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(void)miChatPtnPressed:(UIButton *)btn
{
    //mi chat
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return self.managerInfo.count;
            break;
        case 1:
            return self.ptDataSource.count;
            break;
        default:
            return self.commentDetail.count;
            break;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *managerInfIdentifier = @"ManagerDetailCell";
     static NSString *ptInfoIdentifier = @"ManagerProductCell";
    static NSString *commentIdentifier = @"CommentInfoCell";
   
    switch (indexPath.section) {
        case 0:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:managerInfIdentifier];
            if (cell == nil) {
                cell = [self createCellWithReuseIndentifier:managerInfIdentifier];
            }
            __weak ManagerDetailCell *managerCell = (ManagerDetailCell *)cell;
            managerCell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (self.managerInfo.count > 0) {
                [managerCell  configfWithDataSource:self.managerInfo.firstObject];
                [managerCell.miChatBtn addTarget:self action:@selector(miChatPtnPressed:) forControlEvents:UIControlEventTouchUpInside];
            }
           
        }
            break;
        case 1:
            {
                cell = [tableView dequeueReusableCellWithIdentifier:ptInfoIdentifier];
                if (cell == nil) {
                    cell = [self createCellWithReuseIndentifier:ptInfoIdentifier];
                }
                __weak ManagerProductCell *ptCell = (ManagerProductCell *)cell;
                if (self.ptDataSource.count > 0) {
                    [ptCell  configWithDataSource:self.ptDataSource[indexPath.row]];
                }
                
            }
            break;
            
        default:
            {
                cell = [tableView dequeueReusableCellWithIdentifier:commentIdentifier];
                if (cell == nil) {
                    cell = [self createCellWithReuseIndentifier:commentIdentifier];
                }
                __weak CommentInfoCell *commentCell = (CommentInfoCell *)cell;
                if (self.commentDetail.count > 0) {
                    [commentCell configWithDataSource:self.commentDetail[indexPath.row]];
                }
                
            }

            break;
    }

    
    return cell;
    
}


- (UITableViewCell*)createCellWithReuseIndentifier:(NSString *)reuseIdentifier
{
    
    UITableViewCell* cell = [self loadCellFromNib:reuseIdentifier];
    return cell;
}

- (UITableViewCell *)loadCellFromNib:(NSString *)name {
	return [[NSBundle mainBundle] loadNibNamed:name owner:nil options:nil][0];
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
	return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return 180;
            break;
        case 1:
            return 55;
            break;
        default:
        {
            if (self.commentDetail.count > 0) {
                __weak ClientCommentModel *model = self.commentDetail[indexPath.row];
                return model.cellHeight;
            }else{
                return 0;
            }
            
        }
            break;
    }
	
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	return section == 0?0:6;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 1:
        { //Show pt
             _edit = [[BCMEditProductViewController  alloc]initWithProduct:self.ptDataSource[indexPath.row]
                                                                                               success:nil cancel:^{
                                                                                                   [_edit.view removeFromSuperview];
                                                                                                   _edit = nil;
                                                                                               }];
            [self.view addSubview:_edit.view];
        }
            break;
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)dealloc
{
    [_footer free];
}
@end
